package top.meijhm.communitymanagement.common.auth.api;

import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;
import top.meijhm.communitymanagement.common.auth.model.Result;
import top.meijhm.communitymanagement.common.redis.RedisUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

@RestController
@Api(
        value = "CaptchaController",
        description = "用户登录认证"
)
@RequestMapping("/captcha")
@CrossOrigin(origins = "*")
public class CaptchaController {
    @Autowired
    private Producer producer;
    @Autowired
    RedisUtil redisUtil;

    @GetMapping("")
    @ApiOperation(value = "获取验证码code和userKey", notes = "用于登录传值")
    public Result Captcha() throws IOException {
        String key = String.valueOf(new Random().nextInt(1000)) + System.currentTimeMillis();
        String code = producer.createText();
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());
        redisUtil.set(key, code);
        return Result.succeed(
                MapUtil.builder()
                        .put("code", code)
                        .put("userKey", key)
                        .put("captcherImg", base64Img)
                        .build()
        );
    }
}